
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';
import './ColorUtil.dart';

class CommonUtil {

  static const underlineBlack= UnderlineInputBorder(
    borderSide: BorderSide(
      color: Color.fromRGBO(101, 101, 101, 1), // 设置底部线条颜色
      width: 1.0,         // 设置底部线条宽度
    ),
  );

  static const underline= UnderlineInputBorder(
    borderSide: BorderSide(
      color: Color.fromRGBO(214, 214, 214, 1), // 设置底部线条颜色
      width: 1.0,         // 设置底部线条宽度
    ),
  );


  /**
   * 打电话
   */
  static void launchPhone(String phoneNumber) async {
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    if (await launchUrl(launchUri)) {
      await launchUrl(launchUri);
    } else {
      throw 'Could not launch $phoneNumber';
    }
  }

  //视图宽度
  static screenWidth(context){
    return MediaQuery.of(context).size;
  }

  //不能为空
 static isNotBlank(info){
    return info!=null || info != '';
 }

  /**
   * 搜索条
   */
  Widget searchBox(BuildContext context,{String ? keyWord,GestureTapCallback? onTap}){
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.translucent,
      child: Container(
        padding: EdgeInsets.fromLTRB(0, 0, 0, 6),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: Column(
          children: [
            Container(
              decoration: const BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    width: 0.5, // 边框宽度
                    color: Color.fromRGBO(101, 101, 101, 1), // 边框颜色
                  ),
                ),
              ),
              width: CommonUtil.screenWidth(context).width,
              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
              margin: EdgeInsets.fromLTRB(16, 10, 16, 10),
              child: Flex(
                direction: Axis.horizontal,
                children: [
                  const Icon(Icons.search),
                  const SizedBox(width: 20,),
                  if(keyWord != null && keyWord != "")
                    Text(keyWord,style: TextStyle(color:Colors.black)),
                  if(keyWord == null || keyWord == "")
                    const Text("搜索品牌/车系/车型/配置",style: TextStyle(color:ColorUtil.tipBgColor))
                ],
              ),
            ),
            const SizedBox(height: 2,),
            const Divider(height: 1,),
            SizedBox(height: 10,)
          ],
        ),
      ),
    );
  }


  /**
   * 搜索条圆角
   */
  Widget searchBorder(BuildContext context,{String ? keyWord,GestureTapCallback? onTap}){
    TextEditingController _controller=TextEditingController();
    void onSearch() {
      final query = _controller.text.trim();
      if (query.isNotEmpty) {
        // 执行搜索逻辑
        print('开始搜索：$query');
        // 这里可以调用 API、跳转页面等
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入关键词')),
        );
      }
    }
    void clearInput() {
      _controller.clear();
      // 可选：自动聚焦回输入框
      FocusScope.of(context).requestFocus(FocusNode());
    }

    return  Container(
      padding: const EdgeInsets.fromLTRB(16.0,6.0,16.0,6.0),
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      height: 46,
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _controller,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(vertical: 10.0),
                hintText: '搜索品牌/车系/车型/配置',
                hintStyle: TextStyle(fontSize: 13),
                prefixIcon: Icon(Icons.search),
                suffixIcon: _controller.text.isNotEmpty
                    ? IconButton(
                  icon: Icon(Icons.clear, size: 20),
                  onPressed: clearInput,
                )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(
                    color: ColorUtil.lineColor, // 边框颜色
                    width: 1.0,         // 边框宽度
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: ColorUtil.tipBgColor, // 焦点时边框颜色
                    width: 1.0,
                  ),
                ),
              ),
              onSubmitted: (_) => onSearch(), // 支持键盘回车搜索
            ),
          ),
          SizedBox(width: 8),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.white, // 设置背景色
            ),
            onPressed: onSearch,
            child: Text('搜索', style: TextStyle(color: Colors.black),),
          ),
        ],
      ),
    );
  }
  /**
   * 保存图片到本地
   */
  saveLocalImage(GlobalKey _globalKey,imgUrl) async {
    RenderRepaintBoundary boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage();
    var byteData = await (image.toByteData(format: imgUrl));
    if (byteData != null) {
      final result = await ImageGallerySaverPlus.saveImage(byteData.buffer.asUint8List());
      print(result);
    }
  }


  /**
   * 网络下载
   */
  //url地址"https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg"
  saveNetworkImage(String url) async {
    var response = await Dio().get(
        url,
        options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaverPlus.saveImage(
        // Uint8List.fromList(response.data) as Uint8List,
        response.data,
        quality: 60,
        name: "hello");
      print(result);
  }

  /**
   * 保存gif图片
   * String fileUrl = "https://hyjdoc.oss-cn-beijing.aliyuncs.com/hyj-doc-flutter-demo-run.gif";
   */
  saveNetworkGifFile(String fileUrl) async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.gif";
    await Dio().download(fileUrl, savePath);
    final result = await ImageGallerySaverPlus.saveFile(savePath, isReturnPathOfIOS: true);
    print(result);
    // Utils.toast("$result");
  }

  /**
   * 保存视频
   *  String fileUrl = "https://s3.cn-north-1.amazonaws.com.cn/mtab.kezaihui.com/video/ForBiggerBlazes.mp4";
   */
  saveNetworkVideoFile(String fileUrl) async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
      print((count / total * 100).toStringAsFixed(0) + "%");
    });
    final result = await ImageGallerySaverPlus.saveFile(savePath);
    print(result);
    // Utils.toast("$result");
  }

  callPhone(String s) {
    launchPhone(s);
  }


}

CommonUtil commonUtil = CommonUtil();

